package com.lz.myblog.controller;

import com.lz.myblog.entity.Admininfo;
import com.lz.myblog.repository.AdmininfoRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpSession;
import java.util.List;


@Controller
@RequestMapping("/adminlogin")
public class AdminLoginController {
    @Autowired
    AdmininfoRepository admininfoRepository;

    @RequestMapping("/out")
    public String out(HttpSession session){
        session.invalidate();  //清空sess内容
        return "admin/login";
    }
    @RequestMapping("/index")  //后台首页
    public String index(){
        return "admin/adminindex";
    }

    @RequestMapping("/login")
    public String login(String username, String password, String vercode , Model model, HttpSession session){
        //获取session中的验证码
        String sRand = session.getAttribute("sRand").toString();

        if(!sRand.equalsIgnoreCase(vercode)){  //加感叹号验证码不相等
            model.addAttribute("msg","验证码错误,请重试");
            return "admin/login";
        }
        List<Admininfo> list = admininfoRepository.findByAdminnameEquals(username);
        if (list.size()==0){   //判断用户名是否存在
            model.addAttribute("msg","管理员用户名不存在");
            return "admin/login";
        }
        Admininfo admininfo = list.get(0);
        if (admininfo.getAdminpwd().equals(password)){
            //登录成功
            //记录当前登录用户
            session.setAttribute("loginadmin",admininfo);

            return "redirect:index";  //跳转到后台管理页面

        }else {
            model.addAttribute("msg","管理员密码错误");
            return "admin/login";
        }
    }
}
